<script>
import {
  create,
  page,
  remove,
  statusOptions,
  update,
  updateStatus,
  trigger as triggerJobTask
} from "@/api/robot/jobTask";
import { options as taskPushUnitOptions } from "@/api/robot/robotTaskAdPushUnit";
import Crontab from "@/components/Crontab";
import { globalLoading, isNull } from "@/utils/service";
import { getAdminId, hasRole } from "@/utils/auth";

export default {
  name: "index",
  components: {
    Crontab
  },
  data() {
    return {
      table: {
        loading: false,
        data: [],
        pages: 1,
        total: 0
      },
      query: {
        pageNo: 1,
        pageSize: 10,
        lookMe: true,
        name: "",
        status: undefined,
        adId: undefined,
      },
      options: {
        status: {
          data: [],
          loading: false,
          loadingText: "加载中...."
        },
        pushTaskId: {
          data: [],
          lookMe: true,
          loading: false,
          loadingText: "加载中...."
        }
      },
      form: {
        id: undefined,
        name: "",
        pushTaskIds: [],
        cron: ""
      },
      rules: {
        name: [
          { required: true, message: "请输入定时任务名称", trigger: "blur" },
          { min: 2, max: 32, message: "长度 2 到 32 个字符", trigger: "blur" }
        ],
        cron: [
          { required: true, message: "请点击右方按钮生成 CRON 表达式", trigger: "blur" }
        ],
        pushTaskIds: [
          { required: true, message: "请至少选择一个发布任务单元", trigger: "blur" }
        ]
      },
      dialog: {
        title: "创建定时任务",
        visible: false
      },
      openCron: false,
      expression: ""
    };
  },
  created() {
    this.getTable();
    this.getStatusOptions()
  },
  methods: {
    getStatusOptions() {
      this.options.status.loading = true;
      statusOptions().then(r => {
        this.options.status.data = r;
      }).finally(() => {
        this.options.status.loading = false;
      });
    },
    resetQuery() {
      this.query.name = "";
      this.query.status = undefined;
      this.query.adId = undefined;
    },
    getTable() {
      this.table.loading = false;
      page(this.query).then(r => {
        this.table.data = r.list;
        this.table.pages = r.pages;
        this.table.total = r.total;
      }).finally(() => {
        this.table.loading = true;
      });
    },
    async getTaskPushUnitOptions() {
      this.options.pushTaskId.loading = true;
      await taskPushUnitOptions(this.options.pushTaskId.lookMe).then(r => {
        this.options.pushTaskId.data = r;
      }).finally(() => {
        this.options.pushTaskId.loading = false;
      });
    },
    removeReq(id) {
      let loading = globalLoading(this);
      remove(id).then(r => {
        this.$message.success("提交成功");
        this.getTable();
      }).finally(() => {
        loading.close();
      });
    },
    commitForm() {
      let r;
      let _ = this;
      this.$refs["mForm"].validate((valid) => r = valid);
      if (!r) {
        return;
      }
      let loading = globalLoading(this);
      let finalFuc = function() {
        loading.close();
      };
      let successFuc = function(r) {
        _.$message.success("提交成功");
        _.dialog.visible = false;
        _.getTable();
      };
      if (!isNull(this.form.id)) {
        update(this.form).then(successFuc).finally(finalFuc);
      } else {
        create(this.form).then(successFuc).finally(finalFuc);
      }
    },
    updateStatusReq(id, status) {
      let loading = globalLoading(this);
      updateStatus(id, status).then(r => {
        this.$message.success("提交成功");
        this.getTable();
      }).finally(() => {
        loading.close();
      });
    },
    createHandler() {
      this.form.id = undefined;
      this.form.name = "";
      this.form.cron = "";
      this.form.pushTaskIds = [];
      this.options.pushTaskId.lookMe = true;
      this.dialog.title = "创建定时任务";
      this.dialog.visible = true;
    },
    updateHandler(row) {
      this.form.id = row.id;
      this.form.name = row.name;
      this.form.cron = row.cron;
      this.form.pushTaskIds = row.pushTaskIds || [];
      // 查看他人定时任务
      if (hasRole("超级管理员") && String(row.adId) !== String(getAdminId())) {
        this.options.pushTaskId.lookMe = false;
      }
      this.dialog.title = "修改定时任务";
      this.dialog.visible = true;
    },
    handleShowCron() {
      this.expression = this.form.cron;
      this.openCron = true;
    },
    /** 确定后回传值 */
    crontabFill(value) {
      this.form.cron = value;
    },
    pageSizeChange(v) {
      this.query.pageSize = v;
      this.getTable();
    },
    pageNoChange(v) {
      this.query.pageNo = v;
      this.getTable();
    },
    handleCommand(command, row) {
      let _ = this;
      let loading = globalLoading(this);
      let sFuc = function(r) {
        _.$message.success("提交命令成功");
      };
      let fFuc = function() {
        loading.close();
      };
      if (command === "handleRun") {
        triggerJobTask(row.id).then(sFuc).finally(fFuc);
      } else {
        this.$message.error(`不支持该命令 : ${command}`);
      }
    },
    dialogOpen(){
      this.getTaskPushUnitOptions();
    }
  }
};
</script>

<template>
  <div>
    <div style="margin: 10px 0">
      <el-form :model="query" :inline="true" size="mini">
        <el-form-item prop="lookMe" label="查看范围" v-role="'超级管理员'">
          <el-radio-group v-model="query.lookMe" @input="getTable">
            <el-radio-button :label=true>自己</el-radio-button>
            <el-radio-button :label=false>所有人</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="名称" prop="query">
          <el-input v-model="query.name" placeholder="请输入名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            clearable
            @focus="getStatusOptions"
            v-model="query.status"
            placeholder="选择状态"
            :loading="options.status.loading"
            :loading-text="options.status.loadingText"
          >
            <el-option
              v-for="item in options.status.data"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="管理员编号" prop="adId" v-role="'超级管理员'" v-if="!query.lookMe">
          <el-input v-model="query.adId" placeholder="管理员编号" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getTable">搜索</el-button>
          <el-button type="info" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <div>
        <el-button type="success" @click="createHandler" size="mini">创建定时任务</el-button>
      </div>
    </div>

    <div>
      <el-table
        :row-style="{height: '20px'}"
        :cell-style="{padding: '3px 0'}"
        border
        :loading="table.loading"
        :data="table.data"
        height="72vh"
      >
        <el-table-column label="任务编号" align="center" prop="id" />
        <el-table-column label="任务名称" align="center" prop="name" width="500" show-overflow-tooltip />
        <el-table-column label="任务状态" align="center" prop="status" width="80">
          <template v-slot="{row}">
            <el-tag type="success" v-if="row.status === 0">
              初始化中
            </el-tag>
            <el-tag v-if="row.status === 1">
              开启中
            </el-tag>
            <el-tag type="danger" v-if="row.status === 2">
              已暂停
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="管理员编号" align="center" prop="adId" />
        <el-table-column label="cron表达式" align="center" prop="cron" show-overflow-tooltip />

        <el-table-column align="center" label="操作">
          <template v-slot="{row}">
            <el-button type="text" style="font-weight: bold;" size="small" @click="updateHandler(row)">修改</el-button>
            <el-button v-if="row.status === 1" style="color: #ff4757;font-weight: bold;" type="text" size="small"
                       @click="updateStatusReq(row.id,2)">暂停
            </el-button>
            <el-button v-else-if="row.status === 2" style="color: #2ed573;font-weight: bold;" type="text" size="small"
                       @click="updateStatusReq(row.id,1)">启动
            </el-button>
            <el-popconfirm
              style="margin-left: 10px"
              title="确认删除吗？"
              @confirm="removeReq(row.id)"
            >
              <el-button style="color: #ff3838;font-weight: bold;" type="text" size="small" slot="reference">删除
              </el-button>
            </el-popconfirm>

            <el-dropdown style="margin-left: 10px" @command="handleCommand($event,row)">
              <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="handleRun" icon="el-icon-caret-right">执行一次</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div>
      <div style="text-align: center;margin: 10px 0">
        <el-pagination
          background
          layout="sizes,prev, pager, next, jumper, ->, total"
          :total="table.total"
          :page-size="query.pageSize"
          :current-page="query.pageNo"
          :page-count="table.pages"
          :page-sizes="[10,30,50,100]"
          @size-change="pageSizeChange"
          @current-change="pageNoChange"
        >
        </el-pagination>
      </div>
    </div>

    <el-dialog
      @open="dialogOpen"
      :close-on-click-modal=false
      :title="dialog.title"
      :visible.sync="dialog.visible"
      width="650px"
    >
      <el-form :model="form" :rules="rules" size="mini" label-width="40px" append-to-body ref="mForm">
        <el-form-item label="名称" prop="name" label-width="60px">
          <el-input v-model="form.name" placeholder="定时任务名称" maxlength="32" show-word-limit></el-input>
        </el-form-item>

        <el-form-item label="CRON 表达式" prop="cron" label-width="110px">
          <el-input v-model="form.cron" placeholder="点击右方按钮生成 CRON 表达式">
            <template slot="append">
              <el-button type="primary" @click="handleShowCron">
                生成表达式
                <i class="el-icon-time el-icon--right"></i>
              </el-button>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="发布任务单元" prop="pushTaskIds" label-width="110px">
          <el-select
            filterable
            style="width: 74%"
            multiple
            clearable
            v-model="form.pushTaskIds"
            value-key="id"
            placeholder="选择发布任务单元(可单选)"
            :loading-text="options.pushTaskId.loadingText"
            :loading="options.pushTaskId.loading"
          >
            <el-option
              v-for="item in options.pushTaskId.data"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">用户编号 : {{ item.adId }}</span>
            </el-option>
          </el-select>
          <div style="width: 25%;display: inline-block;margin-left: 5px;">
            <el-tooltip effect="dark" content="选择所有即可选择他人发布单元" placement="top">
              <el-radio-group v-model="options.pushTaskId.lookMe" @input="getTaskPushUnitOptions()">
                <el-radio-button :label=true>自己</el-radio-button>
                <el-radio-button :label=false>所有</el-radio-button>
              </el-radio-group>
            </el-tooltip>
          </div>
        </el-form-item>
      </el-form>
      <template slot="footer">
        <el-button type="info" size="medium" @click="dialog.visible = false">取消</el-button>
        <el-button type="primary" size="medium" @click="commitForm">提交</el-button>
      </template>
    </el-dialog>

    <el-dialog title="Cron表达式生成器" :visible.sync="openCron" append-to-body class="scrollbar" destroy-on-close>
      <crontab @hide="openCron=false" @fill="crontabFill" :expression="expression"
               style="height: 65vh;overflow-y: auto"></crontab>
    </el-dialog>
  </div>
</template>

<style scoped>

</style>